function AllReady() {
    const mstform = Ext.getCmp("PayPlanPc");
    const dgrid1 = Ext.getCmp("PayPlanPcD")
    const dgrid2 = Ext.getCmp("PayPlanPcDD")

    //根据项目过滤合同
    //主表通用帮助过滤
    mstform
        .getItem("user_cnt_id")
        .on("beforetriggerclick", function (eOp, ignoreBeforeEvent) {
            return cntMFilter();
        });
    mstform
        .getItem("user_cnt_id")
        .on("helpselected", function (eOp, ignoreBeforeEvent) {
            getCntCz();
            getCntMInfoByPhid();
            getIncomeInspectionSum();
        });
    mstform
        .getItem("PhidPc")
        .on("helpselected", function (eOp, ignoreBeforeEvent) {
            getPcInfo();
            getPcAccInfo();
            //获取合同数量
            getCntCount(() => {
                getCntCz();
                getCntMInfoByPhid();
                getIncomeInspectionSum();
            })
        });
    var TotalGrid = () => {
        //明细是现汇的
        var user_pay_amt_plan = dgrid2.store.data.items.filter((item) => {
            return item.data.user_jsfs == '3';
        })
        //明细不是现汇的
        var user_pay_amt_plan_cd = dgrid2.store.data.items.filter((item) => {
            return item.data.user_jsfs != '3';
        })
        //计划付款金额(现汇)
        mstform.getItem('user_pay_amt_plan').setValue(dgrid2.store.getSum(user_pay_amt_plan, 'ApvAmtFc'));
        //计划付款金额(承兑)
        mstform.getItem('user_pay_amt_plan_cd').setValue(dgrid2.store.getSum(user_pay_amt_plan_cd, 'ApvAmtFc'));
        mstform.getItem("user_overage_yc").setValue(Ext.Number.from(mstform.getItem("user_overage").getValue(), 0) + Ext.Number.from(mstform.getItem("user_rec_amt_forecast").getValue(), 0) - Ext.Number.from(dgrid2.store.getSum(user_pay_amt_plan, 'ApvAmtFc'), 0))
    }
    setTimeout(function () {
        getPcInfo();
        getPcAccInfo();
        //获取合同数量
        getCntCount(() => {
            getCntCz();
            getCntMInfoByPhid();
            getIncomeInspectionSum();
        })
    }, 500)
    // 读取采购应付分析池的下推数据
    readXTData()
    function readXTData() {
        let json = localStorage.getItem("yffxc_to_prjectyc")
        if (!json) return
        json = JSON.parse(json)
        // 整理合计表体数据
        const total_row = []
        const rows = []
        let i_1 = 0
        for (let key in json) {
            i_1++
            const map = json[key]
            const temp = map.reduce((value, item) => {
                const el = { ...item }
                if (!mstform.getItem("user_tqjjfk").getValue()) {
                    mstform.getItem("user_tqjjfk").setValue(el.u_tqjjfk)
                }
                value.PhidSupplyEnt = String(el.u_supply)
                value.PhidSupplyEnt_EXName = el.u_supply_EXName
                value.ConNo = el.pcm_no
                value.PhidRecBank = el.u_rece_bank
                value.PhidRecBank_EXName = el.u_rece_bank_EXName
                value.RecBankAcc = el.u_bank_no
                value.RecAccName = el.u_payee_EXName
                value.ConName = el.u_cnt_name
                value.ConAmtFc = el.u_hthsje
                value.SortId = i_1
                // 全部累计本期到期日期
                value.ApvAmtFc = (Number(value.ApvAmtFc) || 0) + (Number(el.u_dqyfje) || 0)
                value.ApplyAmtFc = (Number(value.ApplyAmtFc) || 0) + (Number(el.u_dqyfje) || 0)
                value.PayableAmtFc = (Number(value.PayableAmtFc) || 0) + (Number(el.u_dqyfje) || 0)
                console.log(`项目检查`, mstform.getItem("PhidPc").getValue());
                if (!(Number(mstform.getItem("PhidPc").getValue()) || 0)) {
                    console.log(`项目id`, el.phid_pc);
                    mstform.getItem('PhidPc').setValue(el.phid_pc)
                    BatchBindCombox([mstform.getItem('PhidPc')])
                }
                execServer(
                    "u_fc3_payplan_pc_d",
                    { phid: el.pcm_phid },
                    (res) => {
                        if (res.count == 0) return;
                        var _data = JSON.parse(res.data)[0].extendObjects;
                        value.user_ljyfkje = Ext.Number.from(_data.user_ljyfkje, 0);
                        value.user_htljyfje = Ext.Number.from(_data.user_htljyfje, 0);
                        value.user_htljfkje = Ext.Number.from(_data.user_htljfkje, 0);
                        value.user_htljspje = Ext.Number.from(_data.user_htljspje, 0);
                        if (Ext.Number.from(el.u_hthsje, 0) == 0) {
                            value.user_ahtljfkbl = 0;
                        } else {
                            value.user_ahtljfkbl = (Ext.Number.from(_data.user_htljfkje, 0) + Ext.Number.from((Number(value.ApvAmtFc) || 0) + (Number(el.u_dqyfje) || 0), 0)) / Ext.Number.from(el.u_hthsje, 0);
                        }
                    }
                );
                return value
            }, {
                "PhId": "",
                "Pphid": "",
                "SortId": 0,
                "PhidSupplyEnt": "0",
                "PhidCustomerEnt": "0",
                "PhidRecBank": "",
                "RecBankAcc": "",
                "PrePayAmt": 0,
                "PrePayAmtFc": 0,
                "PayableAmt": 0,
                "PayableAmtFc": 0,
                "LjPrepayAmt": 0,
                "LjPrepayAmtFc": 0,
                "ApplyAmt": 0,
                "ApplyAmtFc": 0,
                "ApvAmt": 0,
                "ApvAmtFc": 0,
                "FinAmt": 0,
                "FinAmtFc": 0,
                "RealPayAmt": 0,
                "RealPayAmtFc": 0,
                "InvoHaveMoney": 0,
                "PhidCon": "0",
                "ConAmt": 0,
                "ConAmtFc": 0,
                "LjRealPayAmt": 0,
                "LjRealPayAmtFc": 0,
                "LjSettleAmt": 0,
                "LjSettleAmtFc": 0,
                "PaidRate": 0,
                "CurRate": 0,
                "Remark": "",
                "ImpInfo": "",
                "RestAmt": 0,
                "RestAmtFc": 0,
                "ControlAmt": 0,
                "ControlAmtFc": 0,
                "PhidSourcemid": "",
                "PhidSourceid": "",
                "ItemResource": "",
                "ResourceType": "",
                "ResourceBillCode": "",
                "NgInsertDt": null,
                "NgUpdateDt": null,
                "NgRecordVer": 0,
                "CurOrgId": "",
                "Creator": "",
                "Editor": "",
                "PhidEmp": "0",
                "LjConPaidAmtFc": 0,
                "LjConPaidAmt": 0,
                "Payment": "",
                "RestInvAmt": 0,
                "ConPaySettleAmtFc": 0,
                "ConPayAmtFc": 0,
                "ConFinalAmtFc": 0,
                "ConFinalRwdAmtFc": 0,
                "ConInvoAmtFc": 0,
                "ConRate": 0,
                "ConSettleRate": 0,
                "ConIsFixPriceCon": 0,
                "ConStat": "",
                "RecAccName": "",
                "RestHxAmt": 0,
                "RestHxAmtFc": 0,
                "PhidSupplyEnt_EXName": "",
                "PhidCustomerEnt_EXName": "",
                "PhidRecBank_EXName": "",
                "ConNo": "",
                "ConName": "",
                "PhidEmp_EXName": "",
                "PayableAmtFcShow": 0,
                "user_zftk_name": "",
                "user_zftk": "",
                "user_htljyfje": 0,
                "user_htljfkje": 0,
                "user_ljyfkje": 0,
                "user_ahtljfkbl": 0,
                "user_htljspje": 0
            })
            total_row.push(temp)
        }
        // 整理全数据表体
        let i_2 = 0
        const rows_t = JSON.parse(localStorage.getItem("yffxc_to_prjectyc"))
        for (let key in rows_t) {
            const value = rows_t[key]
            value.forEach(el => {
                let zczf = ''
                if (el.u_zczfqrzt == '1') {
                    zczf = '1'
                } else {
                    zczf = '2'
                }
                i_2++
                const els = {
                    "PhId": "",
                    "PhidFcur": "1",
                    "ExchRate": 1,
                    "Pphid": "0",
                    "PhidDet": "",
                    "SortId": 0,
                    "BillType": "",
                    "PhidBill": "",
                    "BillNo": "",
                    "BillName": "",
                    "PhidSupplyEnt": "0",
                    "PhidCustomerEnt": "0",
                    "PhidRecBank": "",
                    "RecBankAcc": "",
                    "PhidFundType": "",
                    "PhidBudgetType": "",
                    "PayType": 1,
                    "PhidCon": "0",
                    "ConAmt": 0,
                    "ConAmtFc": 0,
                    "ApplyAmt": 0,
                    "ApplyAmtFc": 0,
                    "ApvAmt": 0,
                    "ApvAmtFc": 0,
                    "UpApvAmt": 0,
                    "UpApvAmtFc": 0,
                    "FundPlanAmt": 0,
                    "FundPlanAmtFc": 0,
                    "FundPlanBal": 0,
                    "FundPlanBalFc": 0,
                    "FinAmt": 0,
                    "FinAmtFc": 0,
                    "PrePayAmt": 0,
                    "PrePayAmtFc": 0,
                    "RealPayAmt": 0,
                    "RealPayAmtFc": 0,
                    "Remark": "",
                    "ImpInfo": "",
                    "RestAmt": 0,
                    "RestAmtFc": 0,
                    "ControlAmt": 0,
                    "ControlAmtFc": 0,
                    "PhidSourcemid": "",
                    "PhidSourceid": "",
                    "ItemResource": "",
                    "ResourceType": "",
                    "ResourceBillCode": "",
                    "NgInsertDt": null,
                    "NgUpdateDt": null,
                    "NgRecordVer": 0,
                    "CurOrgId": "",
                    "Creator": "",
                    "Editor": "",
                    "PhidInvoType": "",
                    "InvoHaveMoney": 0,
                    "PayPlanWay": 3,
                    "PayableAmt": 0,
                    "PayableAmtFc": 0,
                    "RestHxAmt": 0,
                    "RestHxAmtFc": 0,
                    "AsrFlag": 0,
                    "SplitFlag": 0,
                    "ConSettleAmtFc": 0,
                    "RecAccName": "",
                    "PhidEmp": "0",
                    "PhidProgressPayment": 0,
                    "ProgressPayment": "",
                    "StopFlag": "",
                    "CntAgeDate": null,
                    "PhidCbs": "",
                    "PhidWbs": "",
                    "CurRate": 0,
                    "PayRate": 1,
                    "PhidSplit": "",
                    "TermAmtFc": 0,
                    "TermAmt": 0,
                    "PhidBusType": "",
                    "PhidRecPayType": "",
                    "PhidInnerAcc": "",
                    "PhidFcur_EXName": "人民币",
                    "PhidBusType_EXName": "",
                    "PhidSupplyEnt_EXName": "",
                    "PhidCustomerEnt_EXName": "",
                    "AttGuid": "9010-1c49-a71c-4bbc",
                    "ConNo": "",
                    "ConName": "",
                    "PhidBudgetType_EXName": "",
                    "PhidFundType_EXName": "",
                    "PhidRecBank_EXName": "",
                    "PhidInvoType_EXName": "",
                    "PayableAmtFcShow": 0,
                    "PhidEmp_EXName": "",
                    "PhidCbs_EXName": "",
                    "PhidWbs_EXName": "",
                    "SplitAmt": 0,
                    "BackfillAmtFc": 0,
                    "BackfillAmt": 0,
                    "PhidRecPayType_EXName": "",
                    "ExchangeType": "",
                    "PhidInnerAcc_EXName": "",
                    "ErMode": 1,
                    "user_source_dt": null,
                    "user_zftk_EXName": "",
                    "user_jsfs": "",
                    "user_cdqxsj": "",
                    "user_byzclhzc": "",
                    "user_zfsj": null,
                    "user_ywlx_EXName": "",
                    "user_cgbyzctjfl": "",
                    "user_fbbyzctjfl": "",
                    "user_qx": "",
                    "user_zczfbzezf": "",
                    "user_zftk": "",
                    "user_ywlx": "",
                    "user_bz": ""
                }
                els.PhidSupplyEnt = String(el.u_supply)
                els.PhidSupplyEnt_EXName = el.u_supply_EXName
                els.ConNo = el.pcm_no
                els.user_zftk = el.u_cnt_tklx
                els.user_zftk_EXName = el.u_cnt_tklx_EXName
                els.user_jsfs = el.u_zffs
                els.user_cdqxsj = el.u_hp_dt
                els.PhidRecBank = el.u_rece_bank
                els.PhidRecBank_EXName = el.u_rece_bank_EXName
                els.RecBankAcc = el.tick_taccountno_pcm
                els.RecAccName = el.u_payee_EXName
                els.ResourceType = '采购应付单'
                els.BillNo = el.u_yfdjh
                els.SortId = i_2
                els.user_ywlx = '19'
                els.user_ywlx_EXName = '付材料采购款'
                els.user_source_dt = el.u_yf_dt && el.u_yf_dt.substr(0, 10)
                els.PhidRecPayType = '1'
                els.PhidRecPayType_EXName = '付供应商款'
                els.PayType = '0'
                // 全部累计本期到期日期
                els.ApvAmtFc = (Number(el.u_dqyfje) || 0)
                els.ApplyAmtFc = (Number(el.u_dqyfje) || 0)
                els.PayableAmtFc = (Number(el.u_dqyfje) || 0)
                els.PhidSourceid = el.u_yflx_phid
                els.user_zczfbzezf = zczf
                rows.push(els)
            })
        }
        console.log(`debug整理数据`, total_row, rows);
        dgrid1.getStore().insert(0, total_row)
        dgrid2.getStore().insert(0, rows)
        TotalGrid();
        localStorage.removeItem("yffxc_to_prjectyc")
    }

    function cntMFilter() {
        var PhidPc = mstform.getItem("PhidPc").getValue();
        if (!(Number(PhidPc) || 0)) {
            Ext.Msg.alert("提示", "请先选择项目！");
            mstform.getItem("PhidPc").focus();
            return false;
        } else {
            mstform.getItem("user_cnt_id").setOutFilter({
                phid_pc: PhidPc, //phid_pc 字段是通用帮助中的字段
                bill_type: 1,
            });
            return true;
        }
    }
    //获取合同产值
    function getCntCz() {
        if (!mstform.getItem("user_cnt_id").getValue()) return;
        console.log(mstform.getItem("user_cnt_id").getValue());
        execServer(
            "getCntCz",
            { phid_cnt: mstform.getItem("user_cnt_id").getValue() },
            (res) => {
                console.log(res);
                if (res.count == 0) return;
                const _data = JSON.parse(res.data)[0].extendObjects;
                console.log(_data);
                mstform.getItem("user_cnt_cz").setValue(_data.amt_sum);
            }
        );
    }

    function getCntMInfoByPhid() {
        // BatchBindCombox([user_regional_center])
        execServer(
            "getCntMInfoByPhid",
            { phid: mstform.getItem("user_cnt_id").getValue() },
            function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
                mstform.getItem("user_cnt_amt").setValue(datas.cnt_sum_vat_fc);
            }
        );
    }

    function getIncomeInspectionSum() {
        execServer(
            "getIncomeInspectionSum",
            { phid_pc: mstform.getItem("PhidPc").getValue() },
            function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
                mstform.getItem("user_cnt_srby").setValue(datas.u_by_amt);
            }
        );
    }
    function getPcAccInfo() {
        execServer(
            "getPcAccInfo",
            { phid_pc: mstform.getItem("PhidPc").getValue() },
            (res) => {
                console.log('获取内连账户信息', res);
                if (res.count == 0) return;
                const _data = JSON.parse(res.data)[0].extendObjects;
                const PhidInnerAcc = mstform.getItem("PhidInnerAcc");
                PhidInnerAcc.setValue(_data.phid_acc);
                BatchBindCombox([PhidInnerAcc]);
            }
        );
    }
    //获取合同数量
    getCntCount(() => {
        getCntCz();
        getCntMInfoByPhid();
        getIncomeInspectionSum();
    })
    function getCntCount(fun) {
        if (!mstform.getItem("PhidPc").getValue()) return
        execServer("getCntCount", { type: 1, phid_pc: mstform.getItem("PhidPc").getValue() }, (res) => {
            console.log(res, 'count');
            switch (res.count) {
                case 0:
                    return
                case 1:
                    const _data = JSON.parse(res.data)[0].extendObjects
                    mstform.getItem("user_cnt_id").setValue(_data.phid)
                    BatchBindCombox([mstform.getItem("user_cnt_id")])
                    setTimeout(() => {
                        if (fun) {
                            fun()
                        }
                    }, 200)
            }
        })
    }

    mstform.getItem("PhidRecPayType").setValue(1);
    BatchBindCombox([mstform.getItem("PhidRecPayType")]);

    execServer("GetHrInfo", { id: $appinfo.userID }, (res) => {
        switch (res.count) {
            case 0:
                return
            case 1:
                var _data = JSON.parse(res.data)[0].extendObjects
                mstform.getItem("PhidApplyDept").setValue(_data.deptid)
                mstform.getItem("PhidApplyPsn").setValue(_data.user_id)
                BatchBindCombox([mstform.getItem("PhidApplyDept"), mstform.getItem("PhidApplyPsn")])
        }
    })


    //user_ywlx
    //23[付劳务工工资]
    //20[付分包工程款]
    //19[付材料采购款]
    var fields = ['user_fbbyzctjfl', 'user_cgbyzctjfl'];
    dgrid2.on('beforeedit', function (editor, e) {
        var record = e.record;
        if (isInArr(fields, e.field) == true && record.get('user_byzclhzc') == '1') {
            if ((record.get('user_ywlx') == '23' || record.get('user_ywlx') == '20') && e.field == 'user_cgbyzctjfl') {
                return false;
            } else if (record.get('user_ywlx') == '19' && e.field == 'user_fbbyzctjfl') {
                return false;
            } else {
                return true;
            }
        } else if (isInArr(fields, e.field) == true && (record.get('user_byzclhzc') == '' || record.get('user_ywlx') == '')) {
            Ext.Msg.alert("提示", "请检查[必要支出/灵活支出]和[业务类型]是否填写！");
            return false;
        }
    });
    function isInArr(arr, value) {
        for (let i = 0, len = arr.length; i < len; i++) {
            if (arr[i] == value) {
                return true;
            }
        }
        return false;
    }
    dgrid2.addListener('edit', function (editor, e) {
        if (e.originalValue == e.value) {
            return;
        }
        if (e.field == 'user_zfsj') {
            var record = e.record;
            var user_source_dt = record.get('user_source_dt'); // 来源日期
            if (e.value && user_source_dt) {
                // 将日期字符串转换为Date对象
                var date1 = new Date(user_source_dt);
                var date2 = new Date(e.value);
                // 计算时间差（毫秒）
                var timeDiff = date2.getTime() - date1.getTime();
                // 将毫秒转换为天数（1天=24*60*60*1000毫秒）
                var dayDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
                if (dayDiff > 90) {
                    record.set('user_qx', "2"); // 大于3个月，赋值2
                } else {
                    record.set('user_qx', "1"); // 小于等于3个月，赋值1
                }
            }
        }
        if (e.field == 'user_jsfs' || e.field == 'ApvAmtFc') {
            TotalGrid();
        }
    });

    dgrid1.store.on('add', function (store, records, index, eOpts) {
        Ext.Array.each(records, function (record) {
            execServer(
                "u_fc3_payplan_pc_d",
                { phid: record.get('PhidCon') },
                (res) => {
                    if (res.count == 0) return;
                    var _data = JSON.parse(res.data)[0].extendObjects;
                    record.set('user_ljyfkje', Ext.Number.from(_data.user_ljyfkje, 0));
                    record.set('user_htljyfje', Ext.Number.from(_data.user_htljyfje, 0));
                    record.set('user_htljfkje', Ext.Number.from(_data.user_htljfkje, 0));
                    record.set('user_htljspje', Ext.Number.from(_data.user_htljspje, 0));
                    if (Ext.Number.from(record.get('ConAmtFc'), 0) == 0) {
                        record.set('user_ahtljfkbl', 0)
                    } else {
                        record.set('user_ahtljfkbl', (Ext.Number.from(_data.user_htljfkje, 0) + Ext.Number.from(record.get('ApvAmtFc'), 0)) / Ext.Number.from(record.get('ConAmtFc'), 0));
                    }
                }
            );
        });
        TotalGrid();
    });
    function getPcInfo() {
        if (!mstform.getItem("PhidPc").getValue()) return
        execServer("u_fc3_payplan_pc", { phid: mstform.getItem("PhidPc").getValue() }, (res) => {
            switch (res.count) {
                case 0:
                    return
                case 1:
                    const _data = JSON.parse(res.data)[0].extendObjects
                    mstform.getItem("user_rec_amt").setValue(Ext.Number.from(_data.user_rec_amt, 0))
                    mstform.getItem("user_rec_amt_cd").setValue(Ext.Number.from(_data.user_rec_amt_cd, 0))
                    mstform.getItem("user_byhkdqtsje").setValue(Ext.Number.from(_data.user_byhkdqtsje, 0))
                    mstform.getItem("user_rec_amt_total").setValue(Ext.Number.from(_data.user_rec_amt_total, 0))
                    mstform.getItem("user_rec_amt_total_cd").setValue(Ext.Number.from(_data.user_rec_amt_total_cd, 0))
                    mstform.getItem("user_overage").setValue(Ext.Number.from(_data.user_overage, 0))
                    mstform.getItem("user_rec_amt_forecast").setValue(Ext.Number.from(_data.user_rec_amt_forecast, 0))
                    mstform.getItem("user_rec_amt_forecast_cd").setValue(Ext.Number.from(_data.asuser_rec_amt_forecast_cd, 0))
                    mstform.getItem("user_dqcdje").setValue(Ext.Number.from(_data.user_dqcdje, 0))
                    mstform.getItem("user_overage_yc").setValue(Ext.Number.from(_data.user_overage, 0) + Ext.Number.from(_data.user_rec_amt_forecast, 0) - Ext.Number.from(mstform.getItem("user_pay_amt_plan").getValue(), 0))
            }
        })
    }
}
function beforeSaveEdit() {
    var mstform = Ext.getCmp("PayPlanPc");
    var dgrid = Ext.getCmp("PayPlanPcDD");
    var dstore = dgrid.store;
    var arr = [];
    Ext.each(dstore.data.items, function (record) {
        arr.push({
            user_ywlx: record.get('user_ywlx'),
            user_byzclhzc: record.get('user_byzclhzc'),
            user_fbbyzctjfl: record.get('user_fbbyzctjfl'),
            user_cgbyzctjfl: record.get('user_cgbyzctjfl')
        });
    });
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].user_byzclhzc == '1' && (arr[i].user_ywlx == '20' || arr[i].user_ywlx == '23') && arr[i].user_fbbyzctjfl == '') {
            NGMsg.Error('第' + (i + 1) + '[分包必要支出条件分类]列未填写，请检查！');
            return false;
        }
        if (arr[i].user_byzclhzc == '1' && arr[i].user_ywlx == '19' && arr[i].user_cgbyzctjfl == '') {
            NGMsg.Error('第' + (i + 1) + '[采购必要支出条件分类]列未填写，请检查！');
            return false;
        }
    }
    return true;
}
